package com.sky.task;

import com.sky.constant.MessageConstant;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 定时任务类，定时处理订单状态
 */
@Component
@Slf4j
public class OrdersTask {
    @Autowired
    private OrderMapper orderMapper;
    /**
     * 对超过十五分钟没有支付的订单进行取消
     * 每分钟触发一次
     */
    @Scheduled(cron = "0 * * * * ?")
    public void cancelOrder() {
        log.info("定时任务：处理超时订单");
        List<Orders> ordersList=orderMapper.selectOrdersByStatusAndOrderTimeRange(Orders.PENDING_PAYMENT,null,LocalDateTime.now().minusMinutes(15));//查出所有超时订单
        if(ordersList==null || ordersList.isEmpty()) {//不存在超时订单
            return;
        }
        Orders updateOrders=null;//用于指向新创建的Orders对象，该对象用于更新Orders表
        for (Orders orders : ordersList) {//遍历超时订单集合，取集合元素id，封装一个新的Orders，用于更新Orders表
            updateOrders= Orders.builder().id(orders.getId())
                    .status(Orders.CANCELLED)//订单状态设置为已取消
                    .cancelTime(LocalDateTime.now())
                    .cancelReason(MessageConstant.ORDER_TIME_OUT)
                    .build();
            orderMapper.update(updateOrders);//数据库表更新
        }
    }

    /**
     * 每天上午一点，检查是否有配送中订单，如果有设置为已完成
     */
    @Scheduled(cron = "0 0 1 * * ?")//
    public void completeOrder() {
        log.info("定时任务：完成派送中订单");
        List<Orders> ordersList=orderMapper.selectOrdersByStatusAndOrderTimeRange(Orders.DELIVERY_IN_PROGRESS,null,LocalDateTime.now().minusMinutes(60));
        if(ordersList==null || ordersList.isEmpty()) {
            return;
        }
        Orders updateOrders=null;//用于指向新创建的Orders对象，该对象用于更新Orders表
        for (Orders orders : ordersList) {//遍历超时订单集合，取集合元素id，封装一个新的Orders，用于更新Orders表
            updateOrders= Orders.builder().id(orders.getId())
                    .status(Orders.COMPLETED)//订单状态设置为已取消
                    .deliveryTime(LocalDateTime.now())
                    .build();
            orderMapper.update(updateOrders);//数据库表更新
        }
    }
}
